import {reqCategory1List, reqCategory2List} from "@/api"
import Vue from "vue"
const state = {
    // 一级分类列表
    category1List : []
}
const mutations = {
    // 给一级分类category1List设置一个新值
    set_category1List(state,payload){
        state.category1List = payload.category1List
        state.category1List.forEach((item)=>{
            Vue.set(item,"children",[])
        })
    },
    // 获取二级分类的列表
    set_category2List(state,payload){
        state.category1List[payload.nowCategoryIndex].children = payload.result
    }
}
const actions = {
    // 获取一级分类列表
   async getCategory1List({commit}){
        const result = await reqCategory1List()
        // console.log(result,"result");
        commit("set_category1List",{category1List : result})
    },


    // 获取二级分类列表
   async getCategory2List(store,category1Id){
    // 先判断当前categoryId对应的一级分类children属性上有没有值，如果有则说明已经获取了,所以不需要发送请求
    const nowCategory = store.state.category1List.find(
        (item)=>item.id === category1Id
    )
        // 获取当前category1Id所在的对象在category1List中的下标
    const nowCategoryIndex = store.state.category1List.findIndex(
        (item)=>item.id === category1Id
    )

    console.log(nowCategory);
    if(nowCategory.children.length !==0 ) return
    // 如果当前一级分类没有children属性，则说明没有发过当前id的二级分类请求，则需要重新发送请求
    const result = await reqCategory2List(category1Id)

    store.commit("set_category2List",{nowCategoryIndex,result})
}

}
const getters = {}

export default {
    namespaced : true,
    state,
    mutations,
    actions,
    getters,
}